package com.ky.pro.java.concurrency;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import static com.ky.pro.java.concurrency.algo.FiboUtil.fibo;

/**
 * @ClassName LockConditionMain
 * @Description 使用Lock+Condition实现
 * @Date 2021/11/27 10:16
 * @Author kevin
 **/
public class LockConditionMain {

    public static void main(String[] args) throws InterruptedException {

        long start = System.currentTimeMillis();

        // 在这里创建一个线程或线程池，
        // 异步执行 下面方法

        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        FiboLockTask task = new FiboLockTask(lock, condition);

        new Thread(task).start();

        lock.lock();
        try {
            condition.await();
        } finally {
            lock.unlock();
        }

        // 确保  拿到result 并输出
        System.out.println("异步计算结果为：" + task.getResult());

        System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");

        // 然后退出main线程

    }

    static class FiboLockTask implements Runnable {

        private int result;

        private ReentrantLock lock;

        private Condition condition;

        public FiboLockTask(ReentrantLock lock, Condition condition) {
            this.lock = lock;
            this.condition = condition;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                result = fibo(36);
                condition.signalAll();
            } finally {
                lock.unlock();
            }
        }

        public int getResult() {
            return result;
        }
    }

}
